//
//  SetupViewController.m
//  Seizure
//
//
// Controller for setting up a new account

#import "SetupViewController.h"
#import "NotificationSender.h"
#import "DataManager.h"
#import "PatientTabViewController.h"
#import "CaretakerTabViewController.h"

@implementation SetupViewController

@synthesize name;
@synthesize email;
@synthesize password;
@synthesize passwordConfirmation;
@synthesize userTypeSelect;
const short REGISTER_REQUEST = 1;
NotificationSender* mySender = nil;
BOOL emailExists = NO;

// initalize controller
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"Create Account";
    }
    return self;
}

// Go to the next field if they hit return on keyboard
- (BOOL) textFieldShouldReturn: (UITextField *) textField{
    [self nextPressed: textField];
    return YES;
}

/**
 * Goto next field, or hide keyboard 
 */
- (void) nextPressed: (id) sender
{    
    if( [name isFirstResponder] )
        [email becomeFirstResponder];
    
    else if( [email isFirstResponder] )
        [password becomeFirstResponder];
    
    else if( [password isFirstResponder] )
        [passwordConfirmation becomeFirstResponder];
    
    else if( [passwordConfirmation isFirstResponder] )
        [passwordConfirmation resignFirstResponder];
}

/**
 *  When the background is touch, get rid of keyboard.
 */
- (IBAction) backgroundTouched: (id) sender
{
    [name becomeFirstResponder];
    [name resignFirstResponder];
}

/**
 * Checks to see if email is valid
 */
- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    
    return [emailTest evaluateWithObject:candidate];
}

/**
 * Validiate user input, create new account
 *
 * This method is TRICKY!!!
 * Please read:
 * ---
 * User clicks to create a new account
 * -> If all is successful, we ask for an apns key
 * -> This method then returns (stops)
 * Reguardless if AppDelegate is able to get an APNSKey (user allows push notifications)
 * This method will be called again
 * gotAPNSKey will now be YES, and uploadUserWithPassword: puts the account in the database
 */
- (IBAction) submitClicked
{
    NSString *errorTitle = @"Sorry!";
    NSString *message = nil;
    
    if (name.text.length == 0){
        message = @"Name field cannot be blank";
    }
    if (![self validateEmail:email.text])
    {
        message = @"Invalid email address";
    }
    if (password.text.length < 6)
    {
        message = @"Password cannot be less than 6 characters.";
    }
    if (![password.text isEqualToString:passwordConfirmation.text]){
        message = @"Passwords do not match";
    }
    
    if (message != nil){
        UIAlertView *error = [[UIAlertView alloc] initWithTitle:errorTitle message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil  ];
        [error show];
    }
    else {
        static bool gotAPNSKey = NO;
        DataManager *data = [DataManager sharedInstance];

        if (!gotAPNSKey){
            // creat account in DataManager
            [data createAccountWithEmail:email.text 
                                withName:name.text 
                            withPassword:password.text 
                               isPatient:(userTypeSelect.selectedSegmentIndex == 0)];
            
            // get APNS key (AppDelegate is notified, putting key in DataManager user)
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
             (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
            
            gotAPNSKey = YES;
            
            // App delegate will call this method again reguardless of APNS key success/fail
            return;
        }
        
        if (emailExists)
        {
            // let's change email, try to upload again
            [[data user] setEmail:email.text];
        }
        
        [data uploadUserWithPassword:password.text delegate:self requestType:REGISTER_REQUEST];
        
    }
    
}

#pragma mark -
#pragma mark NetworkData
-(void) DataArrived:(id)dataObject requestType:(int)rtype{
    dispatch_async(dispatch_get_main_queue(), ^(void) {
    
    if (rtype == REGISTER_REQUEST){
        if (dataObject != nil){
            if ([dataObject isKindOfClass:[Account class]]){
                Account *user = (Account*)dataObject;
                DataManager *dm = [DataManager sharedInstance];
                [dm storeAccount:user];   
                
                // after storing user, we can go to the correct controller

                // after popping this viewController [self]: reference will be lost, so we keep it in nav
                id nav = [self navigationController];
                
                [nav setNavigationBarHidden:YES animated:YES];
                [self.navigationController popToRootViewControllerAnimated:NO];
                UITabBarController *newController;
                if (user.isPatient){
                    newController = [[PatientTabViewController alloc] initWithNibName:@"PatientTabViewController" bundle:nil];
                }
                else{
                    newController = [[CaretakerTabViewController alloc] initWithNibName:@"CaretakerTabViewController" bundle:nil];                    
                }
                [nav pushViewController:newController animated:YES];

            }
            else
            {
                // dataObject must be an error string, for some reason couldn't register
                UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:(NSString*)dataObject delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil  ];
                [error show]; 
                
                // email must already exist, only reason for the failure
                emailExists = YES;
            }
        }
        else {
            // register failed
            UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:@"Network failure" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil  ];
            [error show];
        }
    }
    }); // end dispatched code block 
}



#pragma mark - View lifecycle


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
